package com.jingdianjichi.club.gateway.auth;

import cn.dev33.satoken.stp.StpInterface;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.jingdianjichi.club.gateway.entity.AuthPermission;
import com.jingdianjichi.club.gateway.entity.AuthRole;
import com.jingdianjichi.club.gateway.redis.RedisUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展 
 */
@Component
public class StpInterfaceImpl implements StpInterface {
    @Resource
    private RedisUtil redisUtil;

    private String authPermissionPrefix="auth.permission.";

    private String authRolenPrefix="auth.role";

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的权限列表
        //redis缓存 完全信任  ； redis缓存，没有再去调用微服务 不完全信任
       return getAuth(loginId.toString(), authPermissionPrefix);
    }
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        // 返回此 loginId 拥有的角色列表
        return getAuth(loginId.toString(),authRolenPrefix);

    }

    private List<String> getAuth(String loginId,String prefix){
        String authKey= redisUtil.buildKey(prefix,loginId.toString());
        String authValue= redisUtil.get(authKey);
        if(StringUtils.isBlank(authValue)){
            return Collections.emptyList();
        }
        List<String> authList= new LinkedList<>();
        if(authRolenPrefix.equals(prefix)){
            List<AuthRole> roleList = new Gson().fromJson(authValue, new TypeToken<List<AuthRole>>() {
            }.getType());
            //roleKeyList
             authList=roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());

        }else if(authPermissionPrefix.equals(prefix)) {
            List<AuthPermission> roleList = new Gson().fromJson(authValue, new TypeToken<List<AuthPermission>>() {
            }.getType());
            //permission Key list
            authList=roleList.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());

        }
        return authList;
    }
}
